<template>
	<view class="container">
		<!-- 我的球队列表 -->
		<scroll-view class="my-teams" scroll-x="true" show-scrollbar="true">
			<view class="teams-wrapper">
				<!-- 我的球队列表 -->
				<block v-if="myTeams.length > 0">
					<view class="team-item" v-for="(team, index) in myTeams" :key="team.id"
						:class="{'team-item-active': selectedTeam.id === team.id}" @tap="handleTeamClick(team)">
						<view class="avatar-wrapper">
							<image class="team-avatar" :src="team.logo || '/static/avatars/default-avatar.jpg'"
								mode="aspectFill">
							</image>
						</view>
						<text class="team-name">{{team.name}}</text>
					</view>
				</block>
				<!-- 创建球队按钮 -->
				<view class="team-item create-team" @tap="handleCreateTeam" v-if="myTeams.length < 3">
					<view class="create-btn">
						<text class="plus-icon">+</text>
						<text class="create-text">创建球队</text>
					</view>
				</view>
				<view class="team-limit-tip" v-else>
					<text>最多创建3个球队</text>
				</view>
			</view>
		</scroll-view>

		<!-- 添加空状态提示 -->
		<view class="empty-state" v-if="myTeams.length === 0">
			<image class="empty-icon" src="/static/images/empty-team-bg.png" mode="aspectFit"></image>
			<text class="empty-text">您暂无球队，赶紧创建我的球队吧</text>
		</view>

		<!-- 球队详情面板 -->
		<view class="team-detail" v-if="selectedTeam && myTeams.length > 0">
			<!-- 数据概览 -->
			<view class="stats-bar">
				<view class="stat-item" v-for="(stat, index) in teamStats" :key="index">
					<text class="stat-value">{{stat.value}}</text>
					<text class="stat-label">{{stat.label}}</text>
				</view>
			</view>

			<!-- 球队简介 -->
			<view class="team-info">
				<view class="info-section">
					<text class="info-label">球队名称</text>
					<text class="info-content">{{selectedTeam.name}}</text>
				</view>
				<view class="info-section">
					<text class="info-label">球队简介</text>
					<text class="info-content">{{selectedTeam.description || '暂无简介'}}</text>
				</view>

				<!-- 球队归属 -->
				<view class="info-section">
					<text class="info-label">球队归属地</text>
					<text class="info-content">{{location}}</text>
				</view>

				<!-- 操作按钮组 -->
				<view class="action-buttons">
					<button class="action-btn invite" @tap="handleInvite">
						<image class="btn-icon" src="/static/icons/invite.png" mode="aspectFit"></image>
						<text>邀请入队</text>
					</button>
					<button class="action-btn publish" @tap="handlePublishActivity">
						<image class="btn-icon" src="/static/icons/activity.png" mode="aspectFit"></image>
						<text>发起活动</text>
					</button>
				</view>
			</view>

			<!-- 功能导航 -->
			<view class="function-nav">
				<view class="nav-item" v-for="(nav, index) in navItems" :key="index" @tap="handleNavClick(nav.type)">
					<image class="nav-icon" :src="nav.icon"></image>
					<text class="nav-text">{{nav.text}}</text>
				</view>
			</view>

			<!-- 近期活动 -->
			<view class="section">
				<view class="section-header" @tap="toggleActivities">
					<view class="header-left">
						<text class="section-title">近期活动</text>
						<text class="count">({{recentActivities.length}})</text>
					</view>
					<view class="arrow" :class="{ 'expanded': showActivities }">
						<text>›</text>
					</view>
				</view>
				<view class="activity-list" v-show="showActivities">
					<block v-if="recentActivities.length > 0">
						<activity-item v-for="activity in recentActivities" :key="activity.id" :activity="activity">
						</activity-item>
					</block>
					<view class="empty-tip" v-else>暂无活动</view>
				</view>
			</view>

			<!-- 动态列表 -->
			<view class="section">
				<view class="section-header" @tap="togglePosts">
					<view class="header-left">
						<text class="section-title">球队动态</text>
						<text class="count">({{teamPosts.length}})</text>
					</view>
					<view class="arrow" :class="{ 'expanded': showPosts }">
						<text>›</text>
					</view>
				</view>
				<view class="post-list" v-show="showPosts">
					<view class="post-item" v-for="(post, index) in teamPosts" :key="index">
						<image class="post-avatar" :src="post.avatar"></image>
						<view class="post-content">
							<text class="post-user">{{post.userName}}</text>
							<text class="post-text">{{post.content}}</text>
							<text class="post-time">{{post.time}}</text>
						</view>
					</view>
					<view class="empty-tip" v-if="teamPosts.length === 0">暂无动态</view>
				</view>
			</view>

			<!-- 解散球队按钮 -->
			<view class="dissolve-section">
				<button class="dissolve-btn" @tap="confirmDissolve">解散球队</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		myCreateTeam,
		getTeams,
		delTeams
	} from '@/api/youqiu/team'
	import {
		getAreaByAreaCode
	} from '@/api/common/area'
	import ActivityItem from '@/components/activity-item/index.vue'

	export default {
		components: {
			ActivityItem
		},
		data() {
			return {
				myTeams: [],
				selectedTeam: {},
				userInfo: {},
				shareTeam: null,
				teamStats: [{
						label: '成员',
						value: '0'
					},
					{
						label: '活动',
						value: '0'
					},
					{
						label: '数据',
						value: '--'
					},
					{
						label: '队费',
						value: '¥0'
					},
					{
						label: '名片',
						value: '--'
					}
				],
				navItems: [
					{
						text: '成员管理',
						icon: '/static/icons/member.png',
						type: 'members'
					},
					{
						text: '球队设置',
						icon: '/static/icons/manage.png',
						type: 'settings'
					},
					{
						text: '球队名片',
						icon: '/static/icons/card.png',
						type: 'card'
					}
				],
				recentActivities: [],
				teamPosts: [],
				location: '未设置',
				showActivities: false,
				showPosts: false
			}
		},
		onLoad() {
			const storage_data = uni.getStorageSync('storage_data')
			if (storage_data && storage_data.vuex_user_info) {
				this.userInfo = storage_data.vuex_user_info
			} else {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
			}

			this.getMyTeamsList()
		},
		onShow() {
			// 页面显示时刷新数据
			this.getMyTeamsList()
			
			// 如果有选中的球队，也刷新球队详情
			if (this.selectedTeam && this.selectedTeam.id) {
				this.loadTeamDetails(this.selectedTeam.id)
			}
		},
		computed: {
			// 如果有他计算属性保留在这里
		},
		methods: {
			// 获取我的球队列表
			getMyTeamsList() {
				myCreateTeam().then(res => {
					if (res.code === 200) {
						this.myTeams = res.data || []
						// 如果有球队数据，默认选中第一个球队
						if (this.myTeams.length > 0) {
							// 如果已有选中的球队，保持选中状态
							if (this.selectedTeam && this.selectedTeam.id) {
								const currentTeam = this.myTeams.find(team => team.id === this.selectedTeam.id)
								if (currentTeam) {
									this.selectTeam(currentTeam)
									return
								}
							}
							// 否则选中第一个球队
							this.selectTeam(this.myTeams[0])
						}
					}
				}).catch(err => {
					console.error('获取球队列表失败:', err)
					uni.showToast({
						title: '获取球队列表失败',
						icon: 'none'
					})
				})
			},

			// 创建球队
			handleCreateTeam() {
				if (this.myTeams.length >= 3) {
					uni.showToast({
						title: '最多只能创建3个球队',
						icon: 'none'
					})
					return
				}
				uni.navigateTo({
					url: '/pages/team/create'
				})
			},

			// 选择球队
			selectTeam(team) {
				// 如果点击的球队是当前选中的球队，不重复加载
				if (this.selectedTeam && this.selectedTeam.id === team.id) {
					return
				}
				this.selectedTeam = team
				// 更新本地存储的球队信息
				uni.setStorageSync('publish_team_info', {
					id: team.id,
					name: team.name
				})
				this.loadTeamDetails(team.id)
			},
			// 加载球队详细信息
			loadTeamDetails(teamId) {
				// 先重置数据，避免显示上一球队的数据
				this.resetTeamDetails()

				// 调用获取球队详情接口
				getTeams(teamId).then(res => {
					if (res.code === 200 && res.data) {
						const data = res.data
						console.log('近期活动数据:', data.activities)

						// 确保数据是数组并且每个活动都有必要的属性
						if (Array.isArray(data.activities)) {
							this.recentActivities = data.activities.map(activity => ({
								...activity,
								id: activity.id || `temp-${Date.now()}`, // 确保有 id
								sysUser: activity.sysUser || {}, // 确保有 sysUser 对象
								teamName: activity.teamName || this.selectedTeam.name // 使用球队名称
							}))
						} else {
							this.recentActivities = []
						}

						console.log('处理后的活动数据:', this.recentActivities)
						// 更新统计数据
						this.teamStats = [{
								label: '成员',
								value: data.memberCount || '0'
							},
							{
								label: '活动',
								value: data.activityCount || '0'
							},
							{
								label: '数据',
								value: data.dataCount || '--'
							},
							{
								label: '队费',
								value: `¥${data.teamFee || '0'}`
							}
						]

						// 更新动态列表
						this.teamPosts = data.teamFeeds || []
					}
				}).catch(err => {
					console.error('获取球队详情失败:', err)
					uni.showToast({
						title: '获取球队详情失败',
						icon: 'none'
					})
				})
			},
			// 重置球队详情数据
			resetTeamDetails() {
				this.teamStats = [{
						label: '成员',
						value: '0'
					},
					{
						label: '活动',
						value: '0'
					},
					{
						label: '数据',
						value: '--'
					},
					{
						label: '队费',
						value: '¥0'
					}
				]
				this.recentActivities = []
				this.teamPosts = []
			},
			handleNavClick(type) {
				switch (type) {
					case 'publish':
						uni.switchTab({
							url: '/pages/publish/index'
						})
						break
					case 'members':
						uni.navigateTo({
							url: `/pages/team/members?teamId=${this.selectedTeam.id}&teamName=${this.selectedTeam.name}`
						})
						break
					case 'settings':
						uni.navigateTo({
							url: `/pages/team/edit?teamId=${this.selectedTeam.id}`
						})
						break
					case 'card':
						uni.navigateTo({
							url: `/pages/team/detail?teamId=${this.selectedTeam.id}`,
							fail: (err) => {
								console.error('跳转球队名片页失败:', err)
								uni.showToast({
									title: '页面跳转失败',
									icon: 'none'
								})
							}
						})
						break
				}
			},
			// 处理邀请入队
			handleInvite() {
				if (!this.userInfo.userId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login'
						})
					}, 500)
					return
				}

				// 设置当前要分享的球队
				this.shareTeam = this.selectedTeam

				// 显示分享菜单
				uni.showShareMenu({
					withShareTicket: true,
					menus: ['shareAppMessage']
				})
				
				// 提示用户点击右上角分享
				uni.showToast({
					title: '点击右上角分享',
					icon: 'none',
					duration: 2000
				})
			},

			// 处理发起活动
			handlePublishActivity() {
				uni.switchTab({
					url: '/pages/publish/index'
				})
			},
			// 更新地址信息
			updateLocation(team) {
				if (!team || !team.province) {
					this.location = '未设置'
					return
				}

				let data = []
				if (team.province && team.province !== '') {
					data[0] = team.province
				}
				if (team.city && team.city !== '') {
					data[1] = team.city
				}
				if (team.district && team.district !== '') {
					data[2] = team.district
				}

				if (data.length === 0) {
					this.location = '未设置'
					return
				}

				getAreaByAreaCode(data).then(res => {
					if (res.code === 200 && res.data) {
						this.location = res.data
					} else {
						this.location = '未设置'
					}
				}).catch(() => {
					this.location = '未设置'
				})
			},
			handleTeamClick(team) {
				// 同时选中该球队
				this.selectTeam(team)
			},
			toggleActivities() {
				this.showActivities = !this.showActivities
			},
			togglePosts() {
				this.showPosts = !this.showPosts
			},
			// 确认解散球队
			confirmDissolve() {
				uni.showModal({
					title: '解散球队',
					content: '确定要解散该球队吗？解散后数据将无法恢复',
					confirmText: '确认解散',
					confirmColor: '#ff0000',
					cancelText: '再想想',
					success: (res) => {
						if (res.confirm) {
							this.dissolveTeam()
						}
					}
				})
			},
			
			// 执行解散操作
			async dissolveTeam() {
				try {
					const res = await delTeams(this.selectedTeam.id)
					if (res.code === 200) {
						uni.showToast({
							title: '球队已解散',
							icon: 'success'
						})
						// 重新获取球队列表
						this.getMyTeamsList()
						// 清空选中的球队
						this.selectedTeam = {}
					} else {
						uni.showToast({
							title: res.msg || '解散失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('解散球队失败:', error)
					uni.showToast({
						title: '解散失败',
						icon: 'none'
					})
				}
			}
		},
		// 分享处理
		onShareAppMessage(res) {
			console.log(res.from)
			console.log(res.target)
			// 如果是从邀请按钮触发的分享
			if (this.shareTeam) {
				const shareInfo = {
					content: '我通过小程序分享了球队邀请函',
					title: `邀请加入${this.shareTeam.name}`,
					path: `pages/team/invite/index?teamId=${this.shareTeam.id}&inviterId=${this.userInfo.userId}&inviterName=${this.userInfo.nickName}`,
					imageUrl: this.shareTeam.logo || '/static/images/invite-default.jpg'
				}
				// 清除分享球队
				this.shareTeam = null
				return shareInfo
			}
			console.log('onShareAppMessage',shareInfo)
			// 默认分享
			return {
				title: '加入我的球队',
				path: 'pages/team/invite/index',
				imageUrl: '/static/images/share-default.jpg'
			}
		},
		watch: {
			// 监听 selectedTeam 的变化
			selectedTeam: {
				handler(newVal) {
					// 当选中的球队变化时，更新地址信息
					this.updateLocation(newVal)
				},
				immediate: true, // 立即执行一次
				deep: true // 深度监听对象的变化
			}
		},
		// 在组件销毁时处理
		onUnload() {
			// 清除本地存储的���信息，免影响其他页面
			uni.removeStorageSync('publish_team_info')
		}
	}
</script>


<style lang="scss" scoped>
	.my-teams {
		background-color: #fff;
		padding: 20rpx 0;
		white-space: nowrap;
		border-bottom: 1rpx solid #eee;
		position: relative;
		height: 200rpx;
	}

	.teams-wrapper {
		display: inline-flex;
		align-items: center;
		padding: 0 20rpx;
		flex-direction: row;
		min-width: 100%;
		box-sizing: border-box;
		height: 100%;
		align-items: center;
		justify-content: flex-end;
	}

	.team-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-right: 30rpx;
		width: 120rpx;

		.avatar-wrapper {
			position: relative;
			margin-bottom: 12rpx;

			&::after {
				content: '';
				position: absolute;
				top: -4rpx;
				left: -4rpx;
				right: -4rpx;
				bottom: -4rpx;
				border: 3rpx solid transparent;
				border-radius: 50%;
				transition: all 0.3s ease;
			}
		}

		&:last-child {
			margin-right: 20rpx;
		}
	}

	.create-team {
		margin-left: auto;
		margin-right: 20rpx !important;
		width: 120rpx;
		height: 120rpx;
	}

	.create-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
		background: #f0f9f0;
		border-radius: 12rpx;
		border: 1rpx dashed #4CAF50;

		.plus-icon {
			font-size: 40rpx;
			color: #4CAF50;
			margin-bottom: 8rpx;
		}

		.create-text {
			font-size: 24rpx;
			color: #4CAF50;
			text-align: center;
		}

		&:active {
			opacity: 0.8;
			transform: scale(0.98);
			transition: all 0.2s ease;
		}
	}

	.team-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		border: 1rpx solid #eee;
	}

	.team-name {
		font-size: 24rpx;
		color: #333;
		width: 100%;
		text-align: center;
		line-height: 1.2;
		padding: 0 8rpx;
		word-break: break-all;
		min-height: 56rpx;
	}

	.team-avatar:active {
		opacity: 0.8;
		transform: scale(0.95);
		transition: all 0.2s ease;
	}

	.team-detail {
		background: #fff;
		margin-top: 20rpx;
	}

	.stats-bar {
		display: flex;
		padding: 30rpx 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.stat-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;

		.stat-value {
			font-size: 32rpx;
			color: #333;
			font-weight: bold;
			margin-bottom: 8rpx;
		}

		.stat-label {
			font-size: 24rpx;
			color: #666;
		}
	}

	.function-nav {
		display: flex;
		padding: 30rpx 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.nav-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;

		.nav-icon {
			width: 48rpx;
			height: 48rpx;
			margin-bottom: 8rpx;
		}

		.nav-text {
			font-size: 24rpx;
			color: #333;
		}
	}

	.section {
		padding: 30rpx 20rpx;
		border-bottom: 1rpx solid #eee;

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			cursor: pointer;
			user-select: none;

			&:active {
				background-color: #f5f5f5;
			}
		}

		.header-left {
			display: flex;
			align-items: center;
		}

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.count {
			font-size: 28rpx;
			color: #999;
			margin-left: 8rpx;
		}

		.arrow {
			width: 32rpx;
			height: 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #999;
			font-size: 32rpx;
			transform: rotate(90deg);
			transition: transform 0.3s ease;

			&.expanded {
				transform: rotate(-90deg);
			}
		}

		.activity-list,
		.post-list {
			transition: max-height 0.3s ease;
		}
	}

	.activity-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;

		.activity-title {
			flex: 1;
			font-size: 28rpx;
			color: #333;
		}

		.activity-time {
			font-size: 24rpx;
			color: #999;
			margin: 0 20rpx;
		}

		.activity-status {
			font-size: 24rpx;
			color: #ff6b35;
		}
	}

	.post-item {
		display: flex;
		padding: 20rpx 0;

		.post-avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			margin-right: 20rpx;
		}

		.post-content {
			flex: 1;
		}

		.post-user {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 8rpx;
		}

		.post-text {
			font-size: 26rpx;
			color: #666;
			line-height: 1.4;
		}

		.post-time {
			font-size: 24rpx;
			color: #999;
			margin-top: 8rpx;
			display: block;
		}
	}

	.empty-tip {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 26rpx;
	}

	.team-info {
		padding: 30rpx;
		background: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.info-section {
		margin-bottom: 20rpx;

		.info-label {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 10rpx;
			display: block;
		}

		.info-content {
			font-size: 30rpx;
			color: #333;
			line-height: 1.5;
		}
	}

	.action-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 30rpx;
		gap: 20rpx;
	}

	.action-btn {
		flex: 1;
		height: 88rpx;
		border-radius: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		border: none;
		padding: 0;

		.btn-icon {
			width: 40rpx;
			height: 40rpx;
			margin-right: 12rpx;
		}

		&.invite {
			background: #f0f9f0;
			color: #4CAF50;
			border: 1rpx dashed #4CAF50;
			font-weight: 500;

			.btn-icon {
				filter: brightness(0) saturate(100%) invert(56%) sepia(93%) 
					   saturate(385%) hue-rotate(78deg) brightness(95%) contrast(87%);
			}
		}

		&.publish {
			background: #ff6b35;
			color: #fff;
			font-weight: 500;
		}

		&:active {
			opacity: 0.8;
			
			transform: scale(0.98);
			transition: all 0.2s ease;
		}
	}

	/* 确保按钮去除默认样式 */
	button::after {
		border: none;
	}

	/* 选中状态样式 */
	.team-item-active {
		.avatar-wrapper::after {
			border-color: #ff6b35;
		}

		.team-name {
			color: #ff6b35;
			font-weight: 500;
		}
	}

	// 添���空状态样式
	.empty-state {
		padding: 60rpx 30rpx;
		text-align: center;
		background: #fff;
		margin-top: 20rpx;
		background-image: url('/static/images/empty-team-bg.png');
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
		min-height: 400rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.empty-icon {
			width: 240rpx;
			height: 240rpx;
			margin-bottom: 20rpx;
		}

		.empty-text {
			font-size: 28rpx;
			color: #999;
			line-height: 1.5;
			background: rgba(255, 255, 255, 0.9);
			padding: 16rpx 32rpx;
			border-radius: 32rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		}
	}

	.activity-wrapper {
		position: relative;
		transform: rotate(-5rpx);
	}

	.team-limit-tip {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 30rpx;
		margin-left: auto;
		
		text {
			font-size: 24rpx;
			color: #999;
			white-space: nowrap;
		}
	}

	.dissolve-section {
		padding: 40rpx 30rpx;
		margin-bottom: env(safe-area-inset-bottom);
	}
	
	.dissolve-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #f5f5f5;
		color: #999;
		font-size: 28rpx;
		border-radius: 40rpx;
		border: none;
		
		&:active {
			opacity: 0.8;
		}
	}
</style>